package com.wall.haven.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Charsets;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import com.wall.haven.entity.BanImage;
import com.wall.haven.mapper.BanImageMapper;
import com.wall.haven.service.IBanImageService;
import com.wall.haven.util.ImageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ChenWangKun
 * @since 2023-10-17
 */
@Service
@EnableScheduling
public class BanImageServiceImpl extends ServiceImpl<BanImageMapper, BanImage> implements IBanImageService {

    /** logger */
    private static final Logger LOGGER = LoggerFactory.getLogger(BanImageServiceImpl.class);

    @Resource
    private BanImageMapper banImageMapper;
    /**
     * 存储黑名单记录
     */
    private BloomFilter<String> banFilter = BloomFilter.create(
            Funnels.stringFunnel(Charsets.UTF_8),1000000,0.04);
    @Override
    @Scheduled(cron = "0 0 0 * * *")
    public void init() {
        LOGGER.info("========更新屏蔽图片列表==========");
        banImageMapper.foreach((resultContext)-> {
            banFilter.put(resultContext.getResultObject());
        });
    }

    @Override
    public void banImage(String imageId) {
        boolean flag = false;
        try {
            flag = this.save(new BanImage(imageId));
        }catch (DuplicateKeyException exception){
            //忽略
        }
        if (flag){
            banFilter.put(imageId);
        }
    }

    @Override
    public void banImageUrl(String url) {
        String imageId = ImageUtil.getImageId(url);
        if (imageId != null) {
            this.banImage(imageId);
        }
    }

    @Override
    public boolean isBanned(String imageId) {
        boolean contain = banFilter.mightContain(imageId);
        //可能存在 进一步查库校验
        if (contain){
            BanImage one = this.getOne(Wrappers.<BanImage>lambdaQuery().eq(BanImage::getImageId, imageId));
            return one != null;
        }
        return false;
    }

    @Override
    public boolean isBannedUrl(String url) {
        String imageId = ImageUtil.getImageId(url);
        if (imageId != null) {
            return this.isBanned(imageId);
        }
        return false;
    }
}
